package com.sinodata.bsm.center.web.action.performance;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.cache.RealTimeViewConfCache;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.expression.BatchCalctor;
import com.sinodata.bsm.center.service.performance.RealTimeService;
import com.sinodata.bsm.center.service.resource.ResTypeService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.vo.RealTimeViewConf;
import com.sinodata.bsm.common.vo.ResType;
import com.sinodata.bsm.common.vo.TopoTooltipConf;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author hehaiyang_itsm
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-17 上午10:19:34          hehaiyang_itsm        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class RealTimeViewAction extends BaseAction<RealTimeViewConf> {
    @Autowired
    RealTimeService realTimeService;

    @Autowired
    ResCache resCache;

    private RealTimeViewConf realTimeViewConf;
    @Autowired
    private RealTimeViewConfCache realTimeViewConfCache;
    @Autowired
    private ResTypeService resTypeService;

    /**
     * 
     */
    private static final long serialVersionUID = 1658635631982746104L;

    public String custom() {
        List<RealTimeViewConf> confis = realTimeService.findAllTypeView();
        List<RealTimeViewConf> newViewConf = confis.subList(0, confis.size() >= 10 ? 10 : confis.size());
        JSONArray array = new JSONArray();
        for (int i = 0; i < newViewConf.size(); i++) {
            JSONObject object = new JSONObject();
            RealTimeViewConf confi = newViewConf.get(i);
            ResType resType = resTypeService.get(confi.getResTypeId());
            if (resType != null) {
                object.element("id", confi.getId());
                object.element("resTypeId", confi.getResTypeId());
                object.element("resTypeName", resType.getName());
                array.add(object);
            }
        }
        Struts2Utils.setRequestAttribute("confis", array);
        return "custom";
    }

    public String freeCustom() {
        return "free-custom";
    }

    public String freeCustomList() {
        List<RealTimeViewConf> confis = new ArrayList<RealTimeViewConf>(realTimeViewConfCache.getAll());
        class TimeViewConfCompare implements Comparator<RealTimeViewConf> {
            @Override
            public int compare(RealTimeViewConf o1, RealTimeViewConf o2) {
                long modifyTimeOne = o1.getModifyTime() == null ? -1 : o1.getModifyTime().getTime();
                long modifyTimeTwo = o2.getModifyTime() == null ? -1 : o2.getModifyTime().getTime();
                int compareValue = modifyTimeOne > modifyTimeTwo ? -1 : 1;
                return compareValue;
            }

        }
        Collections.sort(confis, new TimeViewConfCompare());
        JSONArray array = new JSONArray();
        for (int i = 0; i < confis.size(); i++) {
            JSONObject object = new JSONObject();
            RealTimeViewConf confi = confis.get(i);
            if (confi.getResTypeId() == null) { //自定义性能图
                object.element("name", confi.customName());
                object.element("id", confi.getId());
                array.add(object);
            }
        }
        Struts2Utils.renderJson(array);
        return null;
    }

    /**
     * 保存自定义性能图
     * @return
     */
    public String saveCustom() {
        String name = Struts2Utils.getParameter("name");
        RealTimeViewConf viewConf = new RealTimeViewConf();
        viewConf.setXml("<MetaData name='" + name + "'/>");
        viewConf.setModifyTime(new Date());
        realTimeService.saveRealTimeViewConf(viewConf);
        Struts2Utils.renderJson(viewConf);
        return null;

    }

    /**
     * 保存自定义性能图
     * @return
     */
    public String delCustom() {
        String cid = Struts2Utils.getParameter("cid");
        RealTimeViewConf conf = realTimeService.delRealTimeViewConf(Long.parseLong(cid));
        Struts2Utils.renderJson(conf);
        return null;

    }

    public String tooltip() {
        String resTypeId = request.getParameter("resTypeId");
        request.setAttribute("resTypeId", resTypeId);

        List<TopoTooltipConf> toolTipConfis = new ArrayList<TopoTooltipConf>(realTimeViewConfCache.getAllTooltip());
        class ToolTipCompare implements Comparator<TopoTooltipConf> {
            /* (non-Javadoc)
             * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
             */
            @Override
            public int compare(TopoTooltipConf o1, TopoTooltipConf o2) {
                long modifyTimeOne = o1.getModifyTime() == null ? -1 : o1.getModifyTime().getTime();
                long modifyTimeTwo = o2.getModifyTime() == null ? -1 : o2.getModifyTime().getTime();
                int compareValue = modifyTimeOne > modifyTimeTwo ? -1 : 1;
                return compareValue;
            }
        }
        Collections.sort(toolTipConfis, new ToolTipCompare());
        JSONArray array = new JSONArray();
        List<TopoTooltipConf> newTooltip = toolTipConfis.subList(0, toolTipConfis.size() >= 10 ? 10 : toolTipConfis.size());
        for (int i = 0; i < newTooltip.size(); i++) {
            TopoTooltipConf toolTipConf = newTooltip.get(i);
            JSONObject object = new JSONObject();
            object.element("id", toolTipConf.getId());
            object.element("resTypeId", toolTipConf.getResTypeId());
            ResType resType = resTypeService.get(toolTipConf.getResTypeId());
            object.element("resTypeName", resType.getName());
            array.add(object);
        }
        Struts2Utils.setRequestAttribute("resTypes", array);
        return "tooltip";
    }

    public String common() {
        String resIdStr = request.getParameter("resId");
        if (StringUtils.isEmpty(resIdStr) || !StringUtils.isNumeric(resIdStr)) {
            return null;
        }
        Long resTypeId = ResBean.get(Long.parseLong(resIdStr)).res().getResTypeId();
        request.setAttribute("resId", resIdStr);
        request.setAttribute("resTypeId", resTypeId);
        return "common";
    }

    public String queryConf() {
        String resType = request.getParameter("resTypeId");
        RealTimeViewConf conf = realTimeService.findByResTypeId(Long.parseLong(resType));
        if (conf != null && conf.getXml() != null) {
            Struts2Utils.renderXml(response.encodeURL(conf.getXml()));
        } else {
            Struts2Utils.renderText("false");
        }
        return null;
    }

    public String queryTooltipConf() {
        String resType = request.getParameter("resTypeId");
        TopoTooltipConf conf = realTimeService.findTooltipByResTypeId(Long.parseLong(resType));
        if (conf != null && conf.getXml() != null) {
            Struts2Utils.renderXml(response.encodeURL(conf.getXml()));
        } else {
            Struts2Utils.renderText("false");
        }
        return null;
    }

    public String saveConf() throws UnsupportedEncodingException {
        String resType = request.getParameter("resTypeId");
        RealTimeViewConf conf = realTimeService.findByResTypeId(Long.parseLong(resType));
        if (conf == null) {
            conf = new RealTimeViewConf();
            conf.setResTypeId(Long.parseLong(resType));
        }
        conf.setXml(URLDecoder.decode(request.getParameter("xml"), "utf-8"));
        realTimeService.saveRealTimeViewConf(conf);
        Struts2Utils.renderText(conf.getId() + "");
        return null;
    }

    public String saveTooltipConf() throws UnsupportedEncodingException {
        String resType = request.getParameter("resTypeId");
        TopoTooltipConf conf = realTimeService.findTooltipByResTypeId(Long.parseLong(resType));
        if (conf == null) {
            conf = new TopoTooltipConf();
            conf.setResTypeId(Long.parseLong(resType));
        }
        conf.setXml(URLDecoder.decode(request.getParameter("xml"), "utf-8"));
        realTimeService.saveTooltipConf(conf);
        Struts2Utils.renderText(conf.getId() + "");
        return null;
    }

    public String queryRealData() throws IOException {
        String inStr = URLDecoder.decode(request.getParameter("data"), "utf-8");
        BatchCalctor bc = new BatchCalctor();
        String ret = bc.calcXml(inStr);
        ret = response.encodeURL(ret);
        Struts2Utils.renderXml(ret);
        return null;
    }

    /**
     * 返回所有背景图片的文件路径。
     * 
     */
    public void findAllBgImage() {
        File file = null;
        List<String> list = new ArrayList<String>();
        //获取所有图片文件的路径集合
        file = new File(request.getSession().getServletContext().getRealPath("/resources/images/bg"));
        iteratorDirectory(file, list);
        JSONArray jsonArray = JSONArray.fromObject(list);
        try {
            response.getWriter().write(jsonArray.toString());
            logger.info(jsonArray.toString());
        } catch (IOException e) {
            logger.info("获取资源图片列表失败", e);
        }
    }

    private void iteratorDirectory(File a, List<String> list) {
        File[] fileArr = a.listFiles();
        for (File file : fileArr) {
            if (file.isFile()) {
                list.add(file.getName());
            }
        }

    }

    @Override
    public String list() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    public RealTimeService getRealTimeService() {
        return realTimeService;
    }

    public void setRealTimeService(RealTimeService realTimeService) {
        this.realTimeService = realTimeService;
    }

    public RealTimeViewConf getRealTimeViewConf() {
        return realTimeViewConf;
    }

    public void setRealTimeViewConf(RealTimeViewConf realTimeViewConf) {
        this.realTimeViewConf = realTimeViewConf;
    }

    @Override
    public RealTimeViewConf getModel() {
        return realTimeViewConf;
    }

    @Override
    public String save() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub
    }

    public void test() {
        realTimeService.collectPropertyValues(new Long[] { 1100L });
    }
}
